<template>
  <div class="manualinput">
    <div class="content-box">
      <dl>
        <dt>
          <p>发票信息</p>
          <p class="flex flex-jus-start">
            <span>CNY : </span>
            <input type="text" v-model="total" readonly style="color:#333;font-size: .5rem;font-weight: bold;margin-left:0.2rem;width: 5rem;">
          </p>
        </dt>
        <dd v-if="imageDocId">
          <div @click="showImg" v-if="!imgSrc" style="color:#4ec9fa;">显示发票图片</div>
          <div v-if="imgSrc">
            <img :src="imgSrc" class="invoiceimg">
          </div>
        </dd>
        <dd>
          <div class="input-group flex flex-jus-start">
            <div>发票类型</div>
            <p>{{ invoiceType }}</p>
          </div>
        </dd>
        <dd v-for="item in list" :key="item.index" v-if="item.label" :class="item.children?'nopadding':''">
          <div class="input-group flex flex-jus-start" v-if="!item.children">
            <div>{{ item.label }}<span v-if="item.required" class="red">*</span></div>
            <input type="text" v-model="item.value" @keyup="changeTotal" :readonly="editType" :class="editType?'':'border'"/>
          </div>
          <dl v-if="item.children">
            <dt style="font-weight: bold;color:#000;">{{ item.label }}</dt>
            <dd v-for="w in item.children" :key="w.index"  style="padding-left: .2rem;">
              <dl>
                <!-- <dt></dt> -->
                <dd v-for="x in w.items" :key="x.index" v-if="x.label" style="padding-left:.2rem;padding-right: 0;">
                  <div class="input-group flex flex-jus-start">
                    <div>{{ x.label }}<span v-if="x.required" class="red">*</span></div>
                    <input type="text" v-model="x.value" :readonly="editType" :class="editType?'':'border'">
                  </div>
                </dd>
              </dl>
            </dd>
          </dl>
        </dd>
      </dl>

      <div class="btn-group flex">
        <div class="btn-edit flex" v-if="editType" @click="edit">编辑</div>
        <div class="btn-submit flex" v-else @click="submit">修改</div>
      </div>
    </div>
  </div>
</template>

<script>
import { getInvoiceInfo, getInvoiceImage,addTicket,editCheckInvoiceIsUse } from "../plugins/api"
import { mapMutations } from "vuex"
import { Toast } from "vant-green"
export default {
  name: 'ManualInputView',
  data(){
    return {
      invoiceType : "",
      total       : "",         // 价税合计
      imgSrc      : "",
      list        : [],
      formData    : undefined,
      imageDocId  : undefined,
      editType    : true,
      id:-1,
      invoiceInfo:{},
    }
  },
  components: {},
  methods:{
    ...mapMutations(['setFullLoading']),

    changeTotal(){
      this.invoiceInfo.records.map(v=>{
        if(['fare','totalAmount','Amount'].includes(v.key)){
          this.total = v.value
        }
      })
    },
    edit(){
      this.$store.commit('setFullLoading',true)
      editCheckInvoiceIsUse(this.id).then(res=>{
        if(res.code == 200){
          this.editType = false;
        }else{
          Toast(res.msg)
        }
        this.$store.commit('setFullLoading',false)
      }).catch(err=>{
        Toast(err)
        this.$store.commit('setFullLoading',false)
      })
    },
    submit(){
      console.log('保存修改');
      this.$store.commit('setFullLoading',true)
      // 添加到发票夹
      // 从vuex中获取参数
      let obj = this.invoiceInfo
      function checkObject(o){
        for(let key in o){
          if(!o[key]['value'] && o[key]['required']){
            console.log("必填项未填写:",o);
            return false;
          }
        }
        return true;
      }
      // 检查对象中的属性值是否全部为真
      let result = true; // 默认为true 
          result = checkObject(obj['records']); // 如果有未填写的则会返回false
      if(!result){
        this.$store.commit('setFullLoading',false)
        Toast('有必填项没有填写!')
        return false;
      }

      // 数据重组
      let o = {}
      this.list.map(v=>{
        if(v.children){
          let arr = []
          for(let i = 0;i < v.children.length;i++){
            let o2 = {}
            for(let index = 0;index < v.children[i].items.length;index++){
              o2[v.children[i].items[index]['key']] = v.children[i].items[index]['value']
            }
            arr.push(o2)
          }
          o[v.key] = arr
        }else{
          o[v.key] = v.value
        }

      })
      obj['dataType'] = 'update';
      obj['data'] = o
      obj['data']['id'] = obj.id
      console.log('添加至发票夹:',obj);
      addTicket({...obj}).then(res=>{
        // console.log('添加到发票夹以后需要在vuex中和本页面删除这一条数据!',res);
        this.$store.commit('setFullLoading',false)
        Toast(res.msg)
      }).catch(error=>{
        console.log(error);
        this.$store.commit('setFullLoading',false)
        Toast(error.errMsg)
      })
      this.editType = true;
    },

    showImg(){
      // 获取图片
      if(this.imageDocId){
        this.$store.commit('setFullLoading',true)
        getInvoiceImage(this.formData).then(res=>{
          this.$store.commit('setFullLoading',false)
          if(res.code == 200){
            this.imgSrc = `data:image/png;base64,${res.data.base64String}`;
          }
        }).catch(error=>{
          this.$store.commit('setFullLoading',false)
          Toast(error)
        })
      }
    }
  },
  mounted(){
    let obj = this.$route.query
    console.log('obj:',obj);
    // 长度减一 需要修改 测试测试测试
    let a = obj['invoiceNumber'] //.slice(0,obj['invoiceNumber'].length-1)
    let b = obj['invoiceCode']   //.slice(0,obj['invoiceCode'].length-1)
    this.imageDocId = obj['imageDocId']
    this.formData = new FormData()
    this.formData.append('userId',localStorage.getItem('userId')) // 用户ID
    this.formData.append('invoiceNumber',a) // 发票号
    this.formData.append('invoiceCode',b) // 发票码
    this.formData.append('id',obj['id']) // 列表记录的id
    this.id = obj['id']
    // 获取详情
    getInvoiceInfo(this.formData).then(res=>{
      this.$store.commit('setFullLoading',false)
      if(res.code == 200){
        this.invoiceInfo = res.data;
        this.list = res.data.records
        this.invoiceType = res.data.type
        // 获取票价
        this.list.map(v=>{
          if(['fare','totalAmount','Amount'].includes(v.key)){
            this.total = v.value
          }
        })
      }else{
        Toast(res.msg)
        setTimeout(()=>{
          this.$router.go(-1)
        },1500)
      }
    }).catch(err=>{
      this.$store.commit('setFullLoading',false)
      Toast(err)
      setTimeout(()=>{
        this.$router.go(-1)
      },1500)
    })
  },
  //设置title的钩子
  beforeRouteEnter(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
  beforeRouteUpdate(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
}
</script>
<style>
.van-picker__confirm {
  color:#4273D9!important;
}
</style>
<style scoped>

.content-box {
  background-color: white;
  box-shadow: 0 0.05rem 0.15rem rgba(0, 0, 0, 0.1);
  border-radius: 0.1rem;
  margin:0.25rem;
}
dl {
  font-size: 0.3rem;
}
dl dt,
dl dd {
  color:#777;
  border-bottom: 0.01rem solid #eee;
  padding:0.15rem 0.25rem;
  line-height: 1.7;
}
dl dd {
  line-height: 1;
  padding:0.3rem 0.25rem;
}
.input-group div {
  width: 2.2rem;
}
.input-group p {
  flex: 1;
  word-break: break-word;
}
input {
  text-align: left;
  outline: none;
  border:none;
  -webkit-appearance: none;
  appearance: none;
  font-size: .3rem;
  line-height: 1;
  flex: 1;
}
input::-webkit-input-placeholder {
  color:#ccc;
}
.red {
  color:#FF5F4E;
}

.btn-group {
  width:7.5rem;
  position: fixed;
  left:50%;
  bottom:0;
  z-index: 99;
  transform: translateX(-50%);
  padding:.2rem 0.5rem;
  background-color: white;
  box-shadow: 0 0 0.15rem rgba(0, 0, 0, 0.15);
}
.btn-submit {
  width:5.5rem;
  height:.8rem;
  border-radius: 100rem;
  border:none;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: #4273D9;
  color:white;
  font-size: .3rem;
  margin:0 auto;
}
.btn-edit {
  width:5.5rem;
  height:.8rem;
  border-radius: 100rem;
  border:1px solid #4273D9;
  color:#4273D9;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: white;
  font-size: .3rem;
  margin-right: .25rem;
}
.invoiceimg {
  display: block;
  width: 100%;
}
.nopadding {
  padding: 0!important;
}
input.border {
  border:1px solid #ccc!important;
  border-radius: 0.1rem!important;
  outline: none;
  background-color: white;
  appearance: none;
  padding:0.1rem 0.2rem;
}

</style>